package com.grape.dbmiddle.producer.listener;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.grape.dbmiddle.producer.mapper.TxMiddleMapper;
import com.grape.dbmiddle.producer.mapper.UserMapper;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

@Component
@RabbitListener(queues = "tx-quene-from")
public class FanoutListener {
	@Autowired
	UserMapper userMapper;
	@Autowired
	private AmqpTemplate amqpTemplate;
	@Autowired
	TxMiddleMapper txMiddleMapper;

	@RabbitHandler
	@Transactional
	public void process(String msg){
		System.out.println("获取生产者消息msg:" + msg);
		JSONObject jsonObject = JSONUtil.parseObj(msg);
		String txid = jsonObject.getStr("txid");
		//先查询是否已经接收过此消息
		Map<String, Object> txMiddleInfo = txMiddleMapper.getTxMiddleInfo(txid);
		//数据不为null执行业务
		if(txMiddleInfo==null){
			System.out.println("data:"+jsonObject.getStr("data"));
			//执行相关业务
			userMapper.insert("myx",25);
		}
		txMiddleMapper.inset(txid,2);
		//发送消费端信息-无论执行不执行都要发送消息给消费者有可能是那边更新失败类似于询问是否插入成功
		JSONObject jsonObject1 =new JSONObject();
		jsonObject1.put("txid",txid);
		amqpTemplate.convertAndSend("tx-quene-to", JSONUtil.toJsonStr(jsonObject1));
	}
}